import 'dart:convert';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:crypto/crypto.dart';
import 'package:extended_text/extended_text.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'common/MyTextStyle.dart';
import 'common/constants.dart';
import 'common/osc_user_manager.dart';
import 'common/sp_helper.dart';
import 'data/net/dio_util.dart';
import 'data/repository/repository.dart';
import 'event/event.dart';
import 'event/event_constant.dart';
import 'models/models.dart';
import 'res/colors.dart';
import 'ui/pages/other/navigation.dart';
import 'utils/pd_util.dart';
import 'utils/special_text/my_special_text_span_builder.dart';
import 'utils/special_text/special_text_bean.dart';
import 'utils/string_util.dart';

void main() {
  runApp(new MyApp());
  if(Platform.isAndroid){
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}


class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {

  Color themeColor = Colors.blue;
  Locale locale;


  HttpRepository httpRepository;
  bool thirdParty = false;
  bool debug = true;
  String channel;
  String appVersion = "";

  @override
  Widget build(BuildContext context) {
    if(Platform.isAndroid){
      SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
    // 全局配置子树下的SmartRefresher,下面列举几个特别重要的属性
    return RefreshConfiguration(
        headerBuilder: () {
//          return WaterDropHeader(waterDropColor: Colors.green,);
          return MaterialClassicHeader(color: Colors.green, backgroundColor: Colors.white,);
        },// 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
        footerBuilder:  () {
          return ClassicFooter(
            textStyle: TextStyle(color: Colors.black54),
            loadingIcon: CircularProgressIndicator(
              backgroundColor: Colors.black12,
              valueColor: AlwaysStoppedAnimation(Colors.green),
            ),
          );
        },// 配置默认底部指示器
        headerTriggerDistance: 80.0,        // 头部触发刷新的越界距离
        springDescription:SpringDescription(stiffness: 170, damping: 16, mass: 1.9),// 自定义回弹动画,三个属性值意义请查询flutter api
        maxOverScrollExtent :100, //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
        maxUnderScrollExtent:0, // 底部最大可以拖动的范围
        enableScrollWhenRefreshCompleted: true, //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
        enableLoadingWhenFailed : true, //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
        hideFooterWhenNotFull: false, // Viewport不满一屏时,禁用上拉加载更多功能
        enableBallisticLoad: true, // 可以通过惯性滑动触发加载更多

        child: MaterialApp(
          /*theme: ThemeData.light().copyWith(
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        scaffoldBackgroundColor: Colors.white,
        primaryColor: Colours.app_main,
        accentColor: Colours.app_main,
        indicatorColor: Colors.white,
      ),*/
          theme: new ThemeData(
            brightness: Brightness.light,
            backgroundColor: Colours.bg_page,
            scaffoldBackgroundColor: Colours.bg_page,//作为Scaffold下的Material默认颜色，用于materia应用程序或app内页面的背景色。
            primaryColor: Colours.app_main,//App主要部分的背景色（ToolBar,Tabbar等）
            accentColor: Colours.app_main,//前景色(按钮、文本、覆盖边缘效果等)
            unselectedWidgetColor: Colours.gray_66,//小部件处于非活动(但启用)状态时使用的颜色。例如，未选中的复选框。通常与accentColor形成对比。
            indicatorColor: Colors.white,
            tabBarTheme: TabBarTheme(
              labelColor: Colors.white,
              unselectedLabelColor: Colors.black54,
            ),
//        disabledColor: Colours.gray_33,//无效的部件(widget)的颜色，不管它们的状态如何。例如，一个禁用的复选框(可以选中或不选中)。
//        iconTheme: IconThemeData(color: Colors.blue),
//        accentIconTheme: IconThemeData(color: Colors.blue),
//        primaryIconTheme: IconThemeData(color: Colours.gray_33),
          ),
          locale: locale,
          localizationsDelegates: [
            RefreshLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
//            CustomLocalizations.delegate
          ],
//          supportedLocales: CustomLocalizations.supportedLocales,
          localeResolutionCallback:
              (Locale locale, Iterable<Locale> supportedLocales) {
            //print("change language");
            return locale;
          },

          home: SplashPage(),
          color: Colors.white,
        ),
    );
  }
  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]); //这个方法把状态栏和虚拟按键隐藏掉
    initAsync();
  }

  void initAsync() async {
//    initLocale();
//    loadLocale();
    await SpUtil.getInstance();
    getPageParamFromActivity(ui.window.defaultRouteName);
    initDio();
    if (!mounted) return;
  }

  void initDio() async  {
    DioUtil.openDebug();
    String uuid;
    String appToken;
    String userAgent;
    String sessionKey = "";
    String model = "";
    String osVersion = "";
    Map<String, dynamic> headers = Map();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    appVersion = packageInfo.version;
//    if(Platform.isAndroid) {
//      uuid = DioUtil.getUUID();
//      AndroidDeviceInfo info = await DeviceInfoPlugin().androidInfo;
//      model = info.model;
//      String id = info.id;
//      if (id.length > 0) {
//        model += " Build/" + id;
//      }
//      osVersion = info.version.baseOS;
//      userAgent = "OSChina.NET/1.0 (oscapp; $appVersion; Android $osVersion; $model; $uuid)";
//    } else {
//      IosDeviceInfo info = await DeviceInfoPlugin().iosInfo;
//      uuid = info.identifierForVendor;
//      model = info.utsname.machine;
//      osVersion = info.systemVersion;
//      userAgent = "OSChina.NET/1.0 (oscapp; $appVersion; iPhone $osVersion; $model; $uuid)";
//
//    }
//    uuid = md5.convert(utf8.encode(uuid)).toString();
    appVersion = "4.8.5";
    osVersion = "12.4.0";
    model = "iPhone_6sp";
    uuid = "cad5a44cdce7d1cbb4caab2fa7ec2013";
    String tempUuid = "6A245CF6-AB58-4761-B298-6FCD74C0460D";
    appToken = "3165f3e176f8574691299df69eee82aa4b1c4b31";
    appToken = "ccbf55b0eb2c55fd31634585b7f856aa9d9067e4";
    userAgent = "OSChina.NET/1.0 (oscapp; $appVersion; iPhone $osVersion; $model; $tempUuid)";
//    appToken = DioUtil.getAppToken(codeVersionName: appVersion, versionCode: packageInfo.buildNumber);
    sessionKey = md5.convert(utf8.encode(DateTime.now().millisecondsSinceEpoch.toString() + uuid)).toString();
//    headers = DioUtil.getBaseHeaders(appToken: appToken, uuid: uuid, sessionKey: sessionKey, userAgent: userAgent);

//    DioUtil.getDefOptions().headers = headers;
    BaseOptions options = DioUtil.getBaseOptions();
    options.baseUrl = Constant.OSC_OPEN_API_HOST_URL;
    options.contentType = ContentType.json;
//    options.headers = headers;
    HttpConfig config = new HttpConfig(baseOptions: options);
    DioUtil().setConfig(config);

    httpRepository = new HttpRepository();
    if(!debug) {
    } else {
      checkLogin();
    }

//    int currentTime = DateTime.now().millisecondsSinceEpoch;
//    int saveTime = OscSp.instance.getSaveTime();
//    int expiresIn = OscSp.instance.getExpiresIn();
//    double tempTime = (currentTime - saveTime)/1000;
    if(!OscUserManager().isLogin()){
      autoLogin();
    }
  }

  /*void initLocale(){
    //    _locale = new Locale('en', 'US');//English
    locale = new Locale('zh', 'CH'); //繁體中文（香港）
    //    setLocalizedSimpleValues(localizedSimpleValues);//配置简单多语言资源
    setLocalizedValues(localizedValues); //配置多语言资源
  }*/

  void loadLocale() {
    setState(() {
      LanguageModel model = SpHelper.getLanguageModel();
      if (model != null) {
        locale = new Locale(model.languageCode, model.countryCode);
      } else {
        locale = null;
      }

      String _colorKey = SpHelper.getThemeColor();
      if (themeColorMap[_colorKey] != null)
        themeColor = themeColorMap[_colorKey];
    });
  }

  getPageParamFromActivity(String s) {
//    print("-****** string is $s");
  }

  checkCookie() async{
    PersistCookieJar persistCookieJar;
    List<Cookie> cookies;
    CookieManager cookieManager = DioUtil.getInstance().cookieManager;
    String tempPath;
    Future<Directory> tempDir = getApplicationDocumentsDirectory();
    await tempDir.then((dir){
      tempPath = dir.path;
      try{
        persistCookieJar = new PersistCookieJar(dir: tempPath);
        Uri uri = Uri.parse(Constant.OSC_OPEN_API_HOST_URL);
        cookies = persistCookieJar.loadForRequest(uri);
        if(cookies != null && cookies.isNotEmpty){
          for(Cookie cookie in cookies){
            if(cookie.expires.isAfter(DateTime.now())){
              cookieManager.cookieJar.saveFromResponse(uri, cookies);
            } else {
              OscUserManager().logout();
            }
          }
          if(OscUserManager().isLogin()) {
            DioUtil().getDio().interceptors.add(cookieManager);
          }
        } else {
          OscUserManager.instance.setLogin(false);
        }
      } catch(err){
      }
    });
  }


  checkLogin(){
    if (OscUserManager.getInstance().isLogin()){
      getUserInfo();
    } else {
      if (OscUserManager.getInstance().isRememberPwd()) {
        autoLogin();
      }
    }
  }

  autoLogin() async {
    String userName = OscUserManager.instance.getAccount();
    String password = OscUserManager.instance.getPassword();
    if (!StringUtil.isEmpty(userName) && !StringUtil.isEmpty(password)) {
      await httpRepository.login(account: userName, password:StringUtil.getEncodePassword(password)).then((resp) {
        if (resp.success) {
          OscUserManager().setLogin(true);
          OscUserManager().setUser(resp.result);
          eventBus.emit(EventConstant.LOGIN);
        }
      });
    }
  }

  getUserInfo() async{
    if(OscUserManager().isLogin()){
      await httpRepository.getUserInfoV2(userId: OscUserManager().getUserId()).then((resp){
        if(resp.success){
          OscUserManager().setUser(resp.result);
        }
      });
    }
  }

}

class SplashPage extends StatefulWidget{

  SplashPage({Key key}):super(key:key);
  @override
  _SplashPage createState()=> new _SplashPage();

}

class _SplashPage extends State<SplashPage>{

  bool isStartHomePage = false;

  //页面初始化状态的方法
  @override
  void initState() {
    super.initState();
    //开启倒计时
    countDown();
  }

  @override
  Widget build(BuildContext context) {
//    String text  = ":bowtie:我已经在活动:bowtie:“<a href=\"https://www.oschina.net/event/2312491\" target=\"_blank\">2019源创会·年终盛典</a>”签到！:bowtie:";
//    String text = ":bowtie:[招商银行][89]";
//    String text = "test [微笑][撇嘴]\n<a href=\"https://www.oschina.net/tweet-topic/%E6%88%91%E5%A4%AA%E9%9A%BE%E4%BA%86\">#我太难了#</a> \n<a href=\"https://my.oschina.net/u/1272314\">@胖达panda</a> 大的[色]ss https://blog.csdn.net/qq_27981847/article/details/88013862";
//    text = "<a href=\"https://my.oschina.net/u/1272314\">@胖达panda</a> [发呆][发呆]";
//    text = "<a href=\"https://my.oschina.net/u/1272314\" class=\"referer\" target=\"_blank\">@胖达panda</a>  [发呆][发呆]";
//    text = "在发布文章到“CSDN”时，报错抛出 Error: Evaluation failed: TypeError: Cannot read property &apos;focus&apos; of null at inputTitle (__puppeteer_evaluation_script__:3:8) 在发布文章到“开源中国”时，报错抛出 Error: Evaluation failed: TypeError: <a href='https://www.oschina.net/p/artipub' class='project' target='_blank' title='优雅的文章多平台发布工具ArtiPub'>#ArtiPub#</a>";
    return Container(
      color: Colors.white,
      child: GestureDetector(
        onTap: goToHomePage,//设置页面点击事件
        child: Image.asset(PdUtil.getImagePath("welcome"),fit: BoxFit.cover,),//此处fit: BoxFit.cover用于拉伸图片,使图片铺满全屏
//        child: buildContentText(text),
      ),
    );
  }

  buildContentText(String text){
    return ExtendedText(
      text,
      style: MyTextStyle.TWEET_CONTENT,
      onSpecialTextTap: (dynamic parameter) {
        if(parameter is SpecialTextBean){
          SpecialTextBean bean = parameter;
          print("-----${bean.type}");
        }
      },
      specialTextSpanBuilder: MySpecialTextSpanBuilder(),
      overflow: TextOverflow.ellipsis,
      maxLines: 10,
    );
  }

  void countDown() {
    //设置倒计时三秒后执行跳转方法
    var duration = new Duration(seconds: 3);
    new Future.delayed(duration, goToHomePage);
  }

  void goToHomePage(){
    //如果页面还未跳转过则跳转页面
    if(!isStartHomePage){
      //跳转主页 且销毁当前页面
      Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=>new NavigationPage()), (Route<dynamic> rout)=>false);
      isStartHomePage = true;
    }
  }
}
